package cn.starrysky108.simpleerp.user.entity;

import cn.starrysky108.simpleerp.core.util.entity.IpInfo;
import cn.starrysky108.simpleerp.core.enums.DeviceTypeEnum;
import cn.starrysky108.simpleerp.core.util.HttpUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author Carl Lee
 */
@Data
@NoArgsConstructor
public class OnlineDeviceInfo {
    /**
     * 用户id
     */
    private Long userId;
    /**
     * ip地址
     */
    private String host;

    /**
     * 最后一次登录时间
     */
    private LocalDateTime date = LocalDateTime.now();

    /**
     * 登录设备类型
     */
    private String ua;
    /**
     * 设备类型
     */
    private DeviceTypeEnum deviceType;
    /**
     * refreshToken
     */
    private String refreshToken;
    /**
     * ip信息，需要使用第三方接口来进行初始化，默认不进行初始化
     */
    private IpInfo ipInfo;

    /**
     * 获取ipInfo需要请求第三方接口，耗时比较长,默认构造方法中不进行初始化
     */
    public void initIpInfo() {
        if (this.ipInfo == null && StringUtils.hasText(host)) {
            this.ipInfo = HttpUtil.getIpInfo(host);
        }
    }

    public OnlineDeviceInfo(String refreshToken, Long userId, HttpServletRequest request) {
        this.refreshToken = refreshToken;
        this.host = HttpUtil.getClientIp(request);
        this.ua = request.getHeader("User-Agent");
        this.userId = userId;
        initDeviceType(this.ua);
    }

    /**
     * 根据User-Agent判断用户登录设备类型
     *
     * @param ua User-Agent header
     */
    public void initDeviceType(String ua) {

        Class<DeviceTypeEnum> clazz = DeviceTypeEnum.class;
        for (DeviceTypeEnum type : clazz.getEnumConstants()) {
            try {
                if (ua.matches(type.getType())) {
                    this.deviceType = type;
                    break;
                }
            } catch (Exception e) {
                this.deviceType = DeviceTypeEnum.OTHER;
            }
        }
        if (ObjectUtils.isEmpty(deviceType)) {
            this.deviceType = DeviceTypeEnum.OTHER;
        }
    }

}
